<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="scikit-learn系列五：决策树, 欢迎来到，TWOTO 的博客">
    <meta name="description" content="技术、效率、摄影">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>scikit-learn系列五：决策树 | 欢迎来到，TWOTO 的博客</title>
    <link rel="icon" type="image/png" href="/twoto.png">

    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/DongZhouGu/DongZhouGu.github.io/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/DongZhouGu/DongZhouGu.github.io/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/DongZhouGu/DongZhouGu.github.io/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/DongZhouGu/DongZhouGu.github.io/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/DongZhouGu/DongZhouGu.github.io/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="https://cdn.jsdelivr.net/gh/DongZhouGu/DongZhouGu.github.io/libs/jquery/jquery.min.js"></script>

<style type="text/css" lang="css">
    #loading-container{
        position: fixed;
        top: 0;
        left: 0;
        min-height: 100vh;
        width: 100vw;
        z-index: 9999;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        background: #FFF;
        text-align: center;
        /* loader页面消失采用渐隐的方式*/
        -webkit-transition: opacity 1s ease;
        -moz-transition: opacity 1s ease;
        -o-transition: opacity 1s ease;
        transition: opacity 1s ease;
    }
    .loading-image{
        width: 120px;
        height: 50px;
        transform: translate(-50%);
    }
    
    .loading-image div:nth-child(2) {
        -webkit-animation: pacman-balls 1s linear 0s infinite;
        animation: pacman-balls 1s linear 0s infinite
    }

    .loading-image div:nth-child(3) {
        -webkit-animation: pacman-balls 1s linear .33s infinite;
        animation: pacman-balls 1s linear .33s infinite
    }

    .loading-image div:nth-child(4) {
        -webkit-animation: pacman-balls 1s linear .66s infinite;
        animation: pacman-balls 1s linear .66s infinite
    }

    .loading-image div:nth-child(5) {
        -webkit-animation: pacman-balls 1s linear .99s infinite;
        animation: pacman-balls 1s linear .99s infinite
    }
    
   .loading-image div:first-of-type {
        width: 0;
        height: 0;
        border: 25px solid #49b1f5;
        border-right-color: transparent;
        border-radius: 25px;
        -webkit-animation: rotate_pacman_half_up .5s 0s infinite;
        animation: rotate_pacman_half_up .5s 0s infinite;
    }
    .loading-image div:nth-child(2) {
        width: 0;
        height: 0;
        border: 25px solid #49b1f5;
        border-right-color: transparent;
        border-radius: 25px;
        -webkit-animation: rotate_pacman_half_down .5s 0s infinite;
        animation: rotate_pacman_half_down .5s 0s infinite;
        margin-top: -50px;
    }
    @-webkit-keyframes rotate_pacman_half_up {0% {transform: rotate(270deg)}50% {transform: rotate(1turn)}to {transform: rotate(270deg)}}

    @keyframes rotate_pacman_half_up {0% {transform: rotate(270deg)}50% {transform: rotate(1turn)}to {transform: rotate(270deg)}}

    @-webkit-keyframes rotate_pacman_half_down {0% {transform: rotate(90deg)}50% {transform: rotate(0deg)}to {transform: rotate(90deg)}}

    @keyframes rotate_pacman_half_down {0% {transform: rotate(90deg)}50% {transform: rotate(0deg)}to {transform: rotate(90deg)}}
    
    @-webkit-keyframes pacman-balls {75% {opacity: .7}to {transform: translate(-100px, -6.25px)}}

    @keyframes pacman-balls {75% {opacity: .7}to {transform: translate(-100px, -6.25px)}}
    
   
    .loading-image div:nth-child(3),
    .loading-image div:nth-child(4),
    .loading-image div:nth-child(5),
    .loading-image div:nth-child(6){
        background-color: #49b1f5;
        width: 15px;
        height: 15px;
        border-radius: 100%;
        margin: 2px;
        width: 10px;
        height: 10px;
        position: absolute;
        transform: translateY(-6.25px);
        top: 25px;
        left: 100px;
    }
    .loading-text{
        margin-bottom: 20vh;
        text-align: center;
        color: #2c3e50;
        font-size: 2rem;
        box-sizing: border-box;
        padding: 0 10px;
        text-shadow: 0 2px 10px rgba(0,0,0,0.2);
    }
    @media only screen and (max-width: 500px) {
         .loading-text{
            font-size: 1.5rem;
         }
    }
    .fadeout {
        opacity: 0;
        filter: alpha(opacity=0);
    }
    /* logo出现动画 */
    @-webkit-keyframes fadeInDown{0%{opacity:0;-webkit-transform:translate3d(0,-100%,0);transform:translate3d(0,-100%,0)}100%{opacity:1;-webkit-transform:none;transform:none}}
    @keyframes fadeInDown{0%{opacity:0;-webkit-transform:translate3d(0,-100%,0);}}
 </style>
 <script>
(function () {
    const loaded = function(){
       setTimeout(function(){
            const loader = document.getElementById("loading-container");
            loader.className="fadeout" ;//使用渐隐的方法淡出loading page
            // document.getElementById("body-wrap").style.display="flex";
            setTimeout(function(){
                loader.style.display="none";
            },1000); 
        },1000);//强制显示loading page 1s  
    };
    loaded();
})()
 </script><meta name="generator" content="Hexo 4.2.1"><link rel="alternate" href="/atom.xml" title="欢迎来到，TWOTO 的博客" type="application/atom+xml">
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css">
<link rel="stylesheet" href="/css/prism-line-numbers.css" type="text/css"><style type="text/css" lang="css">
    #loading-container{
        position: fixed;
        top: 0;
        left: 0;
        min-height: 100vh;
        width: 100vw;
        z-index: 9999;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        background: #FFF;
        text-align: center;
        /* loader页面消失采用渐隐的方式*/
        -webkit-transition: opacity 1s ease;
        -moz-transition: opacity 1s ease;
        -o-transition: opacity 1s ease;
        transition: opacity 1s ease;
    }
    .loading-image{
        width: 120px;
        height: 50px;
        transform: translate(-50%);
    }
    
    .loading-image div:nth-child(2) {
        -webkit-animation: pacman-balls 1s linear 0s infinite;
        animation: pacman-balls 1s linear 0s infinite
    }

    .loading-image div:nth-child(3) {
        -webkit-animation: pacman-balls 1s linear .33s infinite;
        animation: pacman-balls 1s linear .33s infinite
    }

    .loading-image div:nth-child(4) {
        -webkit-animation: pacman-balls 1s linear .66s infinite;
        animation: pacman-balls 1s linear .66s infinite
    }

    .loading-image div:nth-child(5) {
        -webkit-animation: pacman-balls 1s linear .99s infinite;
        animation: pacman-balls 1s linear .99s infinite
    }
    
   .loading-image div:first-of-type {
        width: 0;
        height: 0;
        border: 25px solid #49b1f5;
        border-right-color: transparent;
        border-radius: 25px;
        -webkit-animation: rotate_pacman_half_up .5s 0s infinite;
        animation: rotate_pacman_half_up .5s 0s infinite;
    }
    .loading-image div:nth-child(2) {
        width: 0;
        height: 0;
        border: 25px solid #49b1f5;
        border-right-color: transparent;
        border-radius: 25px;
        -webkit-animation: rotate_pacman_half_down .5s 0s infinite;
        animation: rotate_pacman_half_down .5s 0s infinite;
        margin-top: -50px;
    }
    @-webkit-keyframes rotate_pacman_half_up {0% {transform: rotate(270deg)}50% {transform: rotate(1turn)}to {transform: rotate(270deg)}}

    @keyframes rotate_pacman_half_up {0% {transform: rotate(270deg)}50% {transform: rotate(1turn)}to {transform: rotate(270deg)}}

    @-webkit-keyframes rotate_pacman_half_down {0% {transform: rotate(90deg)}50% {transform: rotate(0deg)}to {transform: rotate(90deg)}}

    @keyframes rotate_pacman_half_down {0% {transform: rotate(90deg)}50% {transform: rotate(0deg)}to {transform: rotate(90deg)}}
    
    @-webkit-keyframes pacman-balls {75% {opacity: .7}to {transform: translate(-100px, -6.25px)}}

    @keyframes pacman-balls {75% {opacity: .7}to {transform: translate(-100px, -6.25px)}}
    
   
    .loading-image div:nth-child(3),
    .loading-image div:nth-child(4),
    .loading-image div:nth-child(5),
    .loading-image div:nth-child(6){
        background-color: #49b1f5;
        width: 15px;
        height: 15px;
        border-radius: 100%;
        margin: 2px;
        width: 10px;
        height: 10px;
        position: absolute;
        transform: translateY(-6.25px);
        top: 25px;
        left: 100px;
    }
    .loading-text{
        margin-bottom: 20vh;
        text-align: center;
        color: #2c3e50;
        font-size: 2rem;
        box-sizing: border-box;
        padding: 0 10px;
        text-shadow: 0 2px 10px rgba(0,0,0,0.2);
    }
    @media only screen and (max-width: 500px) {
         .loading-text{
            font-size: 1.5rem;
         }
    }
    .fadeout {
        opacity: 0;
        filter: alpha(opacity=0);
    }
    /* logo出现动画 */
    @-webkit-keyframes fadeInDown{0%{opacity:0;-webkit-transform:translate3d(0,-100%,0);transform:translate3d(0,-100%,0)}100%{opacity:1;-webkit-transform:none;transform:none}}
    @keyframes fadeInDown{0%{opacity:0;-webkit-transform:translate3d(0,-100%,0);}}
 </style>
 <script>
(function () {
    const loaded = function(){
       setTimeout(function(){
            const loader = document.getElementById("loading-container");
            loader.className="fadeout" ;//使用渐隐的方法淡出loading page
            // document.getElementById("body-wrap").style.display="flex";
            setTimeout(function(){
                loader.style.display="none";
            },1000); 
        },1000);//强制显示loading page 1s  
    };
    loaded();
})()
 </script></head>



 <div id="loading-container">
     <p class="loading-text">玩命加载中 . . . </p> 
     <div class="loading-image">
         <div></div>
         <div></div>
         <div></div>
         <div></div> 
         <div></div>
     </div>
 </div><body>
<!--动态线条背景-->
<script type="text/javascript"
color="122 103 238" opacity='0.5' zIndex="-1" count="200"
src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js">
</script>

<header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/mylogo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">欢迎来到，TWOTO 的博客</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/mylogo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">欢迎来到，TWOTO 的博客</div>
        <div class="logo-desc">
            
            技术、效率、摄影
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/DongZhouGu" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/DongZhouGu" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>





<div class="bg-cover pd-header post-cover" style="background-image: url('https://cdn.jsdelivr.net/gh/DongZhouGu/DongZhouGu.github.io/medias/featureimages/16.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">scikit-learn系列五：决策树</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/DongZhouGu/DongZhouGu.github.io/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        height: calc(100vh - 250px);
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/">
                                <span class="chip bg-color">基础知识</span>
                            </a>
                        
                            <a href="/tags/ML%E7%AE%97%E6%B3%95/">
                                <span class="chip bg-color">ML算法</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/" class="post-category">
                                机器学习
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-06-30
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    7.1k
                </div>
                

                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="项目地址传送门，欢迎-star-和-fork-！"><a href="#项目地址传送门，欢迎-star-和-fork-！" class="headerlink" title="项目地址传送门，欢迎 star 和 fork ！"></a>项目地址<a href="https://github.com/DongZhouGu/scikit-learn-ml" target="_blank" rel="noopener">传送门</a>，欢迎 star 和 fork ！</h2><h2 id="1-决策树概述"><a href="#1-决策树概述" class="headerlink" title="1. 决策树概述"></a>1. 决策树概述</h2><p>决策树（Decision Tree）算法是一种基本的分类与回归方法，是最经常使用的数据挖掘算法之一，它的预测结果容易理解，易于向业务部门解释，预测速度快，可以处理离散型数据和连续型数据。</p>
<p>决策树模型呈树形结构，在分类问题中，表示基于特征对实例进行分类的过程。它可以认为是 if-then 规则的集合，也可以认为是定义在特征空间与类空间上的条件概率分布。</p>
<p>决策树学习通常包括 3 个步骤: 特征选择、决策树的生成和决策树的修剪。</p>
<hr>
<h2 id="2-决策树原理"><a href="#2-决策树原理" class="headerlink" title="2. 决策树原理"></a>2. 决策树原理</h2><p>一个叫做 “二十个问题” 的游戏，游戏的规则很简单: 参与游戏的一方在脑海中想某个事物，其他参与者向他提问，只允许提 20 个问题，问题的答案也只能用对或错回答。问问题的人通过推断分解，逐步缩小待猜测事物的范围，最后得到游戏的答案。</p>
<p>一个邮件分类系统，大致工作流程如下: </p>
<p><img src="/medias/loading.gif" data-original="https://cdn.jsdelivr.net/gh/dongzhougu/imageuse1/%E5%86%B3%E7%AD%96%E6%A0%91-%E6%B5%81%E7%A8%8B%E5%9B%BE.jpg" alt="决策树-流程图" title="决策树示例流程图"></p>
<pre><code>首先检测发送邮件域名地址。如果地址为 myEmployer.com, 则将其放在分类 "无聊时需要阅读的邮件"中。
如果邮件不是来自这个域名，则检测邮件内容里是否包含单词 "曲棍球" , 如果包含则将邮件归类到 "需要及时处理的朋友邮件", 
如果不包含则将邮件归类到 "无需阅读的垃圾邮件" 。</code></pre><p>问题来了，在创建决策树的过程中，要先对哪个特征进行分裂？比如上图中的例子，先判断域名地址进行分裂还是先判断包含 “曲棍球” 进行分裂？要回答这个问题，我们需要从信息的量化谈起。</p>
<h3 id="2-1-信息熵-amp-信息增益"><a href="#2-1-信息熵-amp-信息增益" class="headerlink" title="2.1 信息熵 &amp; 信息增益"></a>2.1 信息熵 &amp; 信息增益</h3><p><code>熵（entropy）:</code><br>熵指的是体系的混乱的程度，在不同的学科中也有引申出的更为具体的定义，是各领域十分重要的参量。</p>
<p><code>信息论（information theory）中的熵（香农熵）:</code><br>是一种信息的度量方式，表示信息的混乱程度，也就是说: 信息越有序，信息熵越低。例如: 火柴有序放在火柴盒里，熵值很低，相反，熵值很高。</p>
<p><code>信息增益（information gain）:</code><br>在划分数据集前后信息发生的变化称为信息增益。</p>
<h3 id="2-2-决策树的创建"><a href="#2-2-决策树的创建" class="headerlink" title="2.2 决策树的创建"></a>2.2 决策树的创建</h3><p>决策树的构建过程，就是从训练数据集中归纳出一组分类规则，使它与训练数据矛盾较小的同时具有较强的泛化能力。有了信息增益来量化地选择数据集的划分特征，使决策树的创建过程变得容易了。决策树的创建基本上分为以下几个步骤：</p>
<p> （1）计算数据集划分前的信息熵。<br> （2）遍历所有未作为划分条件的特征，分别计算根据每个特征划分数据集后的信息熵。<br> （3）选择信息增益最大的特征，并使用这个特征作为数据划分节点来划分数据。<br> （4）递归地处理被划分后的所有子数据集，从未被选择的特征里继续选择最优数据划分特征来划分子数据集。</p>
<p>问题来了，递归过程什么时候结束呢？一般来讲，有两个终止条件：一是所有的特征都用完了，即没有新的特征可以用来进一步划分数据集。二是划分后的信息增益足够小了，这个时候就可以停止递归划分了。针对这个停止条件，需要事先选择信息增益的阈值来作为结束递归地条件。</p>
<p>使用信息增益作为特征选择指标的决策树构建算法，称为ID3算法。</p>
<h3 id="2-3-剪枝算法"><a href="#2-3-剪枝算法" class="headerlink" title="2.3 剪枝算法"></a>2.3 剪枝算法</h3><p>使用决策树模型拟合数据时，容易造成过拟合。解决过拟合的方法是对决策树进行剪枝处理。决策树的剪枝有两种思路：前剪枝（Pre-Pruning）和后剪枝（Post-Pruning）。</p>
<h4 id="前剪枝（Pre-Pruning）"><a href="#前剪枝（Pre-Pruning）" class="headerlink" title="前剪枝（Pre-Pruning）"></a>前剪枝（Pre-Pruning）</h4><p> 前剪枝是在构造决策树的同时进行剪枝。在决策树的构建过程中，如果无法进一步降低信息熵，就会停止创建分支。为了避免过拟合，可以设定一个阈值，即使可以继续降低信息熵，也停止继续创建分支。这种方法称为前剪枝。还有一些简单的前剪枝方法，如限制叶子节点的样本个数，当样本个数小于一定的阈值时，即不再继续创建分支。</p>
<h4 id="后剪枝（Post-Pruning）"><a href="#后剪枝（Post-Pruning）" class="headerlink" title="后剪枝（Post-Pruning）"></a>后剪枝（Post-Pruning）</h4><p> 后剪枝是指决策树构建完成之后进行剪枝。剪枝的过程是对拥有同样父节点的一组节点进行检查，判断如果将其合并，信息熵的增加量是否小于某一阈值。如果小于阈值，则这一组节点可以合并成一个节点。后剪枝是目前较普遍的做法。后剪枝的过程是删除一些子树，然后用子树的根节点代替，来作为新的叶子结点。这个新的叶子节点所标识的类别通过大多数原则来确定，即把这个叶子节点里样本最多的类别，作为这个叶子节点的类别。</p>
<p>后剪枝算法有很多种，其中常用的一种称为 <code>降低错误率剪枝法（Reduced-Error Pruning）</code>。其思路是，自底向上，从已经构建好的完全决策树中找出一棵子树，然后用子树的根代替这棵子树，作为新的叶子节点。叶子节点所标识的类别通过大多数原则来确定。这样就构建出了一个新的简化版的决策树。然后使用交叉验证数据集来检测这棵简化版的决策树，看其错误率是否降低了。如果错误率降低了，则可以使用这个简化版的决策树代替完全决策树。否则，还是采用原来的决策树。通过遍历所有的子树，直到针对交叉验证数据集，无法进一步降低错误率为止。</p>
<hr>
<h2 id="3-决策树算法参数"><a href="#3-决策树算法参数" class="headerlink" title="3. 决策树算法参数"></a>3. 决策树算法参数</h2><p><code>scikit-learn</code>使用 <code>sklearn.tree.DecisionTreeClassifier</code> 类来实现决策树分类算法。其中几个典型的参数如下：</p>
<ul>
<li><code>criterion：特征选择算法。</code>一种是基于信息熵，另外一种是基于基尼不纯度。研究表明，这两种算法的差异性不大，对模型准确性没有太大的影响。相对而言，信息熵运算效率会低一些，因为它有对数运算。</li>
<li><code>splitter：创建决策树分支的选项。</code>一种是选择最优的分支创建原则。另外一种是从排名靠前的特征中，随机选择一个特征来创建分支，这个方法和正则项的效果类似，可以避免过拟合。</li>
<li><code>max_depth：</code>指定决策树的最大深度。通过指定该参数，用来解决模型过拟合问题。</li>
<li><code>min_samples_split：</code>这个参数指定能创建分支的数据集的大小，默认是2。如果一个节点的数据样本个数小于这个数值，则不再创建分支。这就是上面介绍的前剪枝的一种方法。</li>
<li><code>min_samples_leaf：</code>叶子节点的最小样本数量，叶子节点的样本数量必须大于等于这个值。这也是上面介绍的另一种前剪枝的方法。</li>
<li><code>max_leaf_nodes：</code>最大叶子节点个数，即数据集最多能划分成几个类别。</li>
<li><code>min_impurity_split：</code>信息增益必须大于等于这个阈值才可以继续分支，否则不创建分支。<br> 从这些参数可以看出，<code>scikit-learn</code>有一系列的参数用来控制决策树的生成过程，从而解决过拟合问题。</li>
</ul>
<hr>
<h2 id="4-示例：预测泰坦尼克号幸存者"><a href="#4-示例：预测泰坦尼克号幸存者" class="headerlink" title="4. 示例：预测泰坦尼克号幸存者"></a>4. 示例：预测泰坦尼克号幸存者</h2><p>众所周知，泰坦尼克号是历史上最严重的一起海难事故。我们通过决策树模型，来预测哪些人可能成为幸存者。<a href="https://www.kaggle.com/c/titanic" target="_blank" rel="noopener">数据集下载</a>，也可以去<a href="https://github.com/DongZhouGu/scikit-learn-ml" target="_blank" rel="noopener">仓库地址</a></p>
<p>数据集中总共有两个文件，都是 csv 格式的数据。其中，train.csv 是训练数据集，包含已标注的训练样本数据。test.csv 是模型进行幸存者预测的测试数据。我们的任务就是根据 train.csv 里的数据训练出决策树模型，然后使用该模型来预测test.csv里的数据，并查看模型的预测效果。</p>
<h3 id="4-1-数据分析"><a href="#4-1-数据分析" class="headerlink" title="4.1 数据分析"></a>4.1 数据分析</h3><p>train.csv 是一个892行、12列的数据表格。意味着我们有 891 个训练样本（扣除表头），每个样本有12个特征。我们需要先分析这些特征，以便决定哪些特征可以用来进行模型训练。</p>
<ul>
<li><code>PassengerId：</code>乘客的ID号，这个是顺序编号，用来唯一地标识一名乘客。这个特征和幸存与否无关，丢弃这个特征。</li>
<li><code>Survived</code>：1表示幸存，0表示遇难。这是标注数据。</li>
<li><code>Pclass</code>：仓位等级。这是个很重要的特征，高仓位的乘客能更快的到达甲板，从而更容易获救。</li>
<li><code>Name</code>：乘客的名字，这个特征和幸存与否无关，丢弃这个特征。</li>
<li><code>Sex</code>：乘客性别。由于救生艇数量不够，船长让妇女和儿童先上救生艇。所以这也是个很重要的特征。</li>
<li><code>Age</code>：乘客的年龄。儿童会优先上救生艇，身强力壮者幸存概率也会高一些。所以这也是个很重要的特征。</li>
<li><code>SibSp</code>：兄弟姐妹同在船上的数量。</li>
<li><code>Parch</code>：同船的父辈人员的数量。</li>
<li><code>Ticket</code>：乘客的票号。这个特征和幸存与否无关，丢弃这个特征。</li>
<li><code>Fare</code>：乘客的体热指标。</li>
<li><code>Cabin</code>：乘客所在的船舱号。实际上这个特征和幸存与否有一定的关系，比如最早被水淹没的船舱位置，其乘客的幸存概率要低一些。但由于这个特征有大量的丢失数据，而且没有更多的数据来对船舱进行归类，因此我们丢弃这个特征的数据。</li>
<li><code>Embarked</code>：乘客登船的港口。我们需要把港口数据转换为数值类型的数据。</li>
</ul>
<p>我们需要加载csv数据。并做一些预处理，包括：</p>
<ul>
<li>提取Survived列的数据作为模型的标注数据。</li>
<li>丢弃不需要的特征数据。</li>
<li>对数据进行转换，以便模型处理。比如把性别数据转换为0和1.</li>
<li>处理缺失的数据。比如年龄这个特征，有很多缺失的数据。</li>
</ul>
<p><code>Pandas</code> 是完成这些任务的理想软件包，我们先把数据从文件里读取出来：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">import</span> pandas <span class="token keyword">as</span> pd
<span class="token keyword">def</span> <span class="token function">read_dataset</span><span class="token punctuation">(</span>fname<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token comment" spellcheck="true"># 指定第一列作为行索引</span>
    data <span class="token operator">=</span> pd<span class="token punctuation">.</span>read_csv<span class="token punctuation">(</span>fname<span class="token punctuation">,</span>index_col<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true"># 丢弃无用的数据</span>
    data<span class="token punctuation">.</span>drop<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string">'Name'</span><span class="token punctuation">,</span><span class="token string">'Ticket'</span><span class="token punctuation">,</span><span class="token string">'Cabin'</span><span class="token punctuation">]</span><span class="token punctuation">,</span>axis<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">,</span>inplace<span class="token operator">=</span><span class="token boolean">True</span><span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true"># 处理性别数据</span>
    data<span class="token punctuation">[</span><span class="token string">'Sex'</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">(</span>data<span class="token punctuation">[</span><span class="token string">'Sex'</span><span class="token punctuation">]</span><span class="token operator">==</span><span class="token string">'male'</span><span class="token punctuation">)</span><span class="token punctuation">.</span>astype<span class="token punctuation">(</span><span class="token string">'int'</span><span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true"># 处理登船港口数据</span>
    labels <span class="token operator">=</span> data<span class="token punctuation">[</span><span class="token string">'Embarked'</span><span class="token punctuation">]</span><span class="token punctuation">.</span>unique<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>tolist<span class="token punctuation">(</span><span class="token punctuation">)</span>
    data<span class="token punctuation">[</span><span class="token string">'Embarked'</span><span class="token punctuation">]</span> <span class="token operator">=</span> data<span class="token punctuation">[</span><span class="token string">'Embarked'</span><span class="token punctuation">]</span><span class="token punctuation">.</span>apply<span class="token punctuation">(</span><span class="token keyword">lambda</span> n<span class="token punctuation">:</span>labels<span class="token punctuation">.</span>index<span class="token punctuation">(</span>n<span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true"># 处理缺失数据</span>
    data <span class="token operator">=</span> data<span class="token punctuation">.</span>fillna<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span>
    <span class="token keyword">return</span> data

train <span class="token operator">=</span> read_dataset<span class="token punctuation">(</span><span class="token string">'./titanic/train.csv'</span><span class="token punctuation">)</span>
train<span class="token punctuation">.</span>head<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>处理完的数据如下：</p>
<p><img src="/medias/loading.gif" data-original="https://cdn.jsdelivr.net/gh/dongzhougu/imageuse1/image-20200630171531856.png" alt="img"></p>
<h3 id="4-2-模型训练"><a href="#4-2-模型训练" class="headerlink" title="4.2 模型训练"></a>4.2 模型训练</h3><p>首先需要把 <code>Survived</code> 列提取出来作为标签，并在原数据集中删除这一列。然后把数据集划分成训练数据集和交叉验证数据集。</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">from</span> sklearn<span class="token punctuation">.</span>model_selection <span class="token keyword">import</span> train_test_split
y <span class="token operator">=</span> train<span class="token punctuation">[</span><span class="token string">'Survived'</span><span class="token punctuation">]</span><span class="token punctuation">.</span>values
X <span class="token operator">=</span> train<span class="token punctuation">.</span>drop<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string">'Survived'</span><span class="token punctuation">]</span><span class="token punctuation">,</span>axis<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">.</span>values
X_train<span class="token punctuation">,</span>X_test<span class="token punctuation">,</span>y_train<span class="token punctuation">,</span>y_test <span class="token operator">=</span> train_test_split<span class="token punctuation">(</span>X<span class="token punctuation">,</span>y<span class="token punctuation">,</span>test_size<span class="token operator">=</span><span class="token number">0.2</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'train dataset: {0}; test dataset: {1}'</span><span class="token punctuation">.</span>format<span class="token punctuation">(</span>X_train<span class="token punctuation">.</span>shape<span class="token punctuation">,</span>X_test<span class="token punctuation">.</span>shape<span class="token punctuation">)</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>输出如下：</p>
<pre class="line-numbers language-python"><code class="language-python">train dataset<span class="token punctuation">:</span> <span class="token punctuation">(</span><span class="token number">712</span><span class="token punctuation">,</span> <span class="token number">7</span><span class="token punctuation">)</span><span class="token punctuation">;</span> test dataset<span class="token punctuation">:</span> <span class="token punctuation">(</span><span class="token number">179</span><span class="token punctuation">,</span> <span class="token number">7</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>接着，使用 <code>scikit-learn</code> 的决策树模型对数据集进行拟合，并观察模型的性能：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">from</span> sklearn<span class="token punctuation">.</span>tree <span class="token keyword">import</span> DecisionTreeClassifier
clf <span class="token operator">=</span> DecisionTreeClassifier<span class="token punctuation">(</span><span class="token punctuation">)</span>
clf<span class="token punctuation">.</span>fit<span class="token punctuation">(</span>X_train<span class="token punctuation">,</span>y_train<span class="token punctuation">)</span>
train_score <span class="token operator">=</span> clf<span class="token punctuation">.</span>score<span class="token punctuation">(</span>X_train<span class="token punctuation">,</span>y_train<span class="token punctuation">)</span>
test_score <span class="token operator">=</span> clf<span class="token punctuation">.</span>score<span class="token punctuation">(</span>X_test<span class="token punctuation">,</span>y_test<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'train score: {0}; test score: {1}'</span><span class="token punctuation">.</span>format<span class="token punctuation">(</span>train_score<span class="token punctuation">,</span>test_score<span class="token punctuation">)</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>输出如下：</p>
<pre class="line-numbers language-python"><code class="language-python">train score<span class="token punctuation">:</span> <span class="token number">0.9859550561797753</span><span class="token punctuation">;</span> test score<span class="token punctuation">:</span> <span class="token number">0.7877094972067039</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>从输出结果可以看出，针对训练样本评分很高，但是针对交叉验证数据集评分较低，两者差距较大。没错，这是过拟合现象。解决决策树过拟合的方法是剪枝，包括前剪枝和后剪枝。不幸的是 <code>scikit-learn</code> 不支持后剪枝，但是提供了一系列模型参数进行前剪枝。例如，可以通过 <code>max_depth</code> 参数限定决策树的深度，当决策树达到限定的深度时，就不再进行分裂了。这样就可以在一定程度上避免过拟合。</p>
<h3 id="4-3-优化模型参数"><a href="#4-3-优化模型参数" class="headerlink" title="4.3 优化模型参数"></a>4.3 优化模型参数</h3><p>我们可以选择一系列的参数值，然后分别计算指定参数训练出来的模型的评分。还可以把参数值和模型评分通过图形画出来，以便直观地发现两者之间的关系。</p>
<p>这里以限制决策树深度 <code>max_depth</code> 为了来介绍模型参数的优化过程。我们先创建一个函数，它使用不同的<code>max_depth</code> 来训练模型，并计算模型评分。</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true"># 参数选择 max_depth</span>
<span class="token keyword">def</span> <span class="token function">cv_score</span><span class="token punctuation">(</span>d<span class="token punctuation">)</span><span class="token punctuation">:</span>
    clf <span class="token operator">=</span> DecisionTreeClassifier<span class="token punctuation">(</span>max_depth<span class="token operator">=</span>d<span class="token punctuation">)</span>
    clf<span class="token punctuation">.</span>fit<span class="token punctuation">(</span>X_train<span class="token punctuation">,</span>y_train<span class="token punctuation">)</span>
    tr_score <span class="token operator">=</span> clf<span class="token punctuation">.</span>score<span class="token punctuation">(</span>X_train<span class="token punctuation">,</span>y_train<span class="token punctuation">)</span>
    cv_score <span class="token operator">=</span> clf<span class="token punctuation">.</span>score<span class="token punctuation">(</span>X_test<span class="token punctuation">,</span>y_test<span class="token punctuation">)</span>
    <span class="token keyword">return</span> <span class="token punctuation">(</span>tr_score<span class="token punctuation">,</span>cv_score<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>接着构造参数范围，在这个范围内分别计算模型评分，并找出评分最高的模型所对应的参数。</p>
<pre class="line-numbers language-dart"><code class="language-dart"><span class="token keyword">import</span> numpy <span class="token operator">as</span> np
depths <span class="token operator">=</span> <span class="token function">range</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">15</span><span class="token punctuation">)</span>
scores <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token function">cv_score</span><span class="token punctuation">(</span>d<span class="token punctuation">)</span> <span class="token keyword">for</span> d <span class="token keyword">in</span> depths<span class="token punctuation">]</span>
tr_scores <span class="token operator">=</span> <span class="token punctuation">[</span>s<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token keyword">for</span> s <span class="token keyword">in</span> scores<span class="token punctuation">]</span>
cv_scores <span class="token operator">=</span> <span class="token punctuation">[</span>s<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token keyword">for</span> s <span class="token keyword">in</span> scores<span class="token punctuation">]</span>
best_score_index <span class="token operator">=</span> np<span class="token punctuation">.</span><span class="token function">argmax</span><span class="token punctuation">(</span>cv_scores<span class="token punctuation">)</span>
best_score <span class="token operator">=</span> cv_scores<span class="token punctuation">[</span>best_score_index<span class="token punctuation">]</span>
best_param <span class="token operator">=</span> depths<span class="token punctuation">[</span>best_score_index<span class="token punctuation">]</span>
<span class="token function">print</span><span class="token punctuation">(</span>scores<span class="token punctuation">)</span>
<span class="token function">print</span><span class="token punctuation">(</span><span class="token string">'best param: {0}； best score： {1}'</span><span class="token punctuation">.</span><span class="token function">format</span><span class="token punctuation">(</span>best_param<span class="token punctuation">,</span>best_score<span class="token punctuation">)</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>输出如下：</p>
<pre class="line-numbers language-css"><code class="language-css">best <span class="token property">param</span><span class="token punctuation">:</span> <span class="token number">4</span>； best score： <span class="token number">0.8212290502793296</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>可以看到，针对模型深度这个参数，最优的值是4，其对应的交叉验证数据集评分为0.82。我们还可以把模型参数和对应的模型评分画出来，更直观地观察其变化规律。</p>
<pre class="line-numbers language-dart"><code class="language-dart"><span class="token keyword">import</span> matplotlib<span class="token punctuation">.</span>pyplot <span class="token operator">as</span> plt
plt<span class="token punctuation">.</span><span class="token function">figure</span><span class="token punctuation">(</span>figsize<span class="token operator">=</span><span class="token punctuation">(</span><span class="token number">6</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">)</span><span class="token punctuation">,</span>dpi<span class="token operator">=</span><span class="token number">144</span><span class="token punctuation">)</span>
plt<span class="token punctuation">.</span><span class="token function">grid</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
plt<span class="token punctuation">.</span><span class="token function">xlabel</span><span class="token punctuation">(</span><span class="token string">'max depth of decision tree'</span><span class="token punctuation">)</span>
plt<span class="token punctuation">.</span><span class="token function">ylabel</span><span class="token punctuation">(</span><span class="token string">'score'</span><span class="token punctuation">)</span>
plt<span class="token punctuation">.</span><span class="token function">plot</span><span class="token punctuation">(</span>depths<span class="token punctuation">,</span>cv_scores<span class="token punctuation">,</span><span class="token string">'.g-'</span><span class="token punctuation">,</span>label<span class="token operator">=</span><span class="token string">'cross-validation score'</span><span class="token punctuation">)</span>
plt<span class="token punctuation">.</span><span class="token function">plot</span><span class="token punctuation">(</span>depths<span class="token punctuation">,</span>tr_scores<span class="token punctuation">,</span><span class="token string">'.r--'</span><span class="token punctuation">,</span>label<span class="token operator">=</span><span class="token string">'training score'</span><span class="token punctuation">)</span>
plt<span class="token punctuation">.</span><span class="token function">legend</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>输出如下：</p>
<p><img src="/medias/loading.gif" data-original="https://cdn.jsdelivr.net/gh/dongzhougu/imageuse1/17634123-8536c1c2cfda1d0f.png" alt="image-20200630171531856"></p>
<p>使用同样的方式，我们可以考察参数 m<code>in_impurity_split</code> 。这个参数用来指定信息熵或基尼不纯度的阈值。当决策树分裂后，其信息增益低于这个阈值，则不再分裂。</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true"># 训练模型，并计算评分</span>
<span class="token keyword">def</span> <span class="token function">cv_score</span><span class="token punctuation">(</span>val<span class="token punctuation">)</span><span class="token punctuation">:</span>
    clf <span class="token operator">=</span> DecisionTreeClassifier<span class="token punctuation">(</span>criterion<span class="token operator">=</span><span class="token string">'gini'</span><span class="token punctuation">,</span> min_impurity_decrease<span class="token operator">=</span>val<span class="token punctuation">)</span>
    clf<span class="token punctuation">.</span>fit<span class="token punctuation">(</span>X_train<span class="token punctuation">,</span> y_train<span class="token punctuation">)</span>
    tr_score <span class="token operator">=</span> clf<span class="token punctuation">.</span>score<span class="token punctuation">(</span>X_train<span class="token punctuation">,</span> y_train<span class="token punctuation">)</span>
    cv_score <span class="token operator">=</span> clf<span class="token punctuation">.</span>score<span class="token punctuation">(</span>X_test<span class="token punctuation">,</span> y_test<span class="token punctuation">)</span>
    <span class="token keyword">return</span> <span class="token punctuation">(</span>tr_score<span class="token punctuation">,</span> cv_score<span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 指定参数范围，分别训练模型，并计算评分</span>
values <span class="token operator">=</span> np<span class="token punctuation">.</span>linspace<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">0.005</span><span class="token punctuation">,</span> <span class="token number">50</span><span class="token punctuation">)</span>
scores <span class="token operator">=</span> <span class="token punctuation">[</span>cv_score<span class="token punctuation">(</span>v<span class="token punctuation">)</span> <span class="token keyword">for</span> v <span class="token keyword">in</span> values<span class="token punctuation">]</span>
tr_scores <span class="token operator">=</span> <span class="token punctuation">[</span>s<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token keyword">for</span> s <span class="token keyword">in</span> scores<span class="token punctuation">]</span>
cv_scores <span class="token operator">=</span> <span class="token punctuation">[</span>s<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token keyword">for</span> s <span class="token keyword">in</span> scores<span class="token punctuation">]</span>

<span class="token comment" spellcheck="true"># 找出评分最高的模型参数</span>
best_score_index <span class="token operator">=</span> np<span class="token punctuation">.</span>argmax<span class="token punctuation">(</span>cv_scores<span class="token punctuation">)</span>
best_score <span class="token operator">=</span> cv_scores<span class="token punctuation">[</span>best_score_index<span class="token punctuation">]</span>
best_param <span class="token operator">=</span> values<span class="token punctuation">[</span>best_score_index<span class="token punctuation">]</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'best param: {0}; best score: {1}'</span><span class="token punctuation">.</span>format<span class="token punctuation">(</span>best_param<span class="token punctuation">,</span> best_score<span class="token punctuation">)</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 画出模型参数与模型评分的关系</span>
plt<span class="token punctuation">.</span>figure<span class="token punctuation">(</span>figsize<span class="token operator">=</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">6</span><span class="token punctuation">)</span><span class="token punctuation">,</span> dpi<span class="token operator">=</span><span class="token number">144</span><span class="token punctuation">)</span>
plt<span class="token punctuation">.</span>grid<span class="token punctuation">(</span><span class="token punctuation">)</span>
plt<span class="token punctuation">.</span>xlabel<span class="token punctuation">(</span><span class="token string">'threshold of entropy'</span><span class="token punctuation">)</span>
plt<span class="token punctuation">.</span>ylabel<span class="token punctuation">(</span><span class="token string">'score'</span><span class="token punctuation">)</span>
plt<span class="token punctuation">.</span>plot<span class="token punctuation">(</span>values<span class="token punctuation">,</span> cv_scores<span class="token punctuation">,</span> <span class="token string">'.g-'</span><span class="token punctuation">,</span> label<span class="token operator">=</span><span class="token string">'cross-validation score'</span><span class="token punctuation">)</span>
plt<span class="token punctuation">.</span>plot<span class="token punctuation">(</span>values<span class="token punctuation">,</span> tr_scores<span class="token punctuation">,</span> <span class="token string">'.r--'</span><span class="token punctuation">,</span> label<span class="token operator">=</span><span class="token string">'training score'</span><span class="token punctuation">)</span>
plt<span class="token punctuation">.</span>legend<span class="token punctuation">(</span><span class="token punctuation">)</span>
plt<span class="token punctuation">.</span>show<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>输出如下：</p>
<pre class="line-numbers language-python"><code class="language-python">best param<span class="token punctuation">:</span> <span class="token number">0.0005102040816326531</span><span class="token punctuation">;</span> best score<span class="token punctuation">:</span> <span class="token number">0.8100558659217877</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><img src="/medias/loading.gif" data-original="https://cdn.jsdelivr.net/gh/dongzhougu/imageuse1/image-20200630181702264.png" alt="image-20200630174835975"></p>
<p>这里把[0,0.005]等分50份，以每个等分点作为信息增益阈值来训练一次模型。可以看到，训练数据集的评分急速下降，且训练评分和测试评分都保持较低水平，说明模型欠拟合。我们可以把决策树特征选择的基尼不纯度改为信息熵，即把参数<code>criterion</code>的值改为<code>'entropy'</code>观察图形的变化。</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
clf <span class="token operator">=</span> DecisionTreeClassifier<span class="token punctuation">(</span>criterion<span class="token operator">=</span><span class="token string">'entropy'</span><span class="token punctuation">,</span> min_impurity_decrease<span class="token operator">=</span>val<span class="token punctuation">)</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p><img src="/medias/loading.gif" data-original="https://cdn.jsdelivr.net/gh/dongzhougu/imageuse1/image-20200630174835975.png" alt="image-20200630175057127"></p>
<h3 id="4-4-模型参数选择工具包"><a href="#4-4-模型参数选择工具包" class="headerlink" title="4.4 模型参数选择工具包"></a>4.4 模型参数选择工具包</h3><p>上面的模型参数优化过程存在两个问题。其一，数据不稳定，即数据集每次都是随机划分的，选择出来的最优参数在下一次运行时就不是最优的了。其二，不能一次选择多个参数，例如，想要考察 <code>max_depth</code>和<code>min_samples_leaf</code>两个结合起来的最优参数就无法实现。</p>
<p>问题一的原因是，每次把数据集划分为训练样本和交叉验证样本时，是随机划分的，这样导致每次的训练数据集是有差异的，训练出来的模型也有差异。解决这个问题的方法是多次计算，求平均值。具体来讲，就是针对模型的某个特定的参数，多次划分数据集，多次训练模型，计算出这个参数对应的模型的最低评分、最高评分以及评价评分。问题二的解决办法比较简单，把代码再优化一下，能处理多个参数组合即可。</p>
<p>所幸，我们不需要从头实现这些代码。<code>scikit-learn</code>在 <code>sklearn.model_selection</code>包里提供了大量模型选择和评估工具供我们使用。针对以上问题，可以使用 <code>GridSearchCV</code> 类来解决。</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">from</span> sklearn<span class="token punctuation">.</span>model_selection <span class="token keyword">import</span> GridSearchCV
thresholds <span class="token operator">=</span> np<span class="token punctuation">.</span>linspace<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">0.5</span><span class="token punctuation">,</span> <span class="token number">50</span><span class="token punctuation">)</span>
param_grid <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token string">'min_impurity_split'</span><span class="token punctuation">:</span> thresholds<span class="token punctuation">}</span>
clf <span class="token operator">=</span> GridSearchCV<span class="token punctuation">(</span>DecisionTreeClassifier<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> param_grid<span class="token punctuation">,</span> cv<span class="token operator">=</span><span class="token number">5</span><span class="token punctuation">,</span>return_train_score<span class="token operator">=</span><span class="token boolean">True</span><span class="token punctuation">)</span>
clf<span class="token punctuation">.</span>fit<span class="token punctuation">(</span>X<span class="token punctuation">,</span> y<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"best param: {0}\nbest score: {1}"</span><span class="token punctuation">.</span>format<span class="token punctuation">(</span>clf<span class="token punctuation">.</span>best_params_<span class="token punctuation">,</span> clf<span class="token punctuation">.</span>best_score_<span class="token punctuation">)</span><span class="token punctuation">)</span>
plot_curve<span class="token punctuation">(</span>thresholds<span class="token punctuation">,</span> clf<span class="token punctuation">.</span>cv_results_<span class="token punctuation">,</span> xlabel<span class="token operator">=</span><span class="token string">'gini thresholds'</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>输出如下：</p>
<pre class="line-numbers language-python"><code class="language-python">best param<span class="token punctuation">:</span> <span class="token punctuation">{</span><span class="token string">'min_impurity_split'</span><span class="token punctuation">:</span> <span class="token number">0.19387755102040816</span><span class="token punctuation">}</span>
best score<span class="token punctuation">:</span> <span class="token number">0.82045069361622</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>其中关键的参数是<code>param_grid</code>，它是一个字典，键对应的值是一个列表。<code>GridSearchCV</code>会枚举列表里的所有值来构建模型，最终得出指定参数值的平均评分及标准差。另外一个关键参数是cv，它用来指定交叉验证数据集的生成规则，代码中的 cv=5 ，表示每次计算都把数据集分成 5 份，拿其中一份作为交叉验证数据集，其他的作为训练数据集。最终得出的最优参数及最优评分保存在 <code>clf.best_params</code> 和 <code>clf.best_score</code>里。此外，<code>clf.cv_results_</code>保存了计算过程的所有中间结果。我们可以拿这个数据来画出模型参数与模型评分的关系图，如下所示:</p>
<p><img src="/medias/loading.gif" data-original="https://cdn.jsdelivr.net/gh/dongzhougu/imageuse1/image-20200630175057127.png" alt="image-20200630181702264"></p>
<p>接下来看一下如何在多组参数之间选择最优的参数组合：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">from</span> sklearn<span class="token punctuation">.</span>model_selection <span class="token keyword">import</span> GridSearchCV
entropy_thresholds <span class="token operator">=</span> np<span class="token punctuation">.</span>linspace<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">50</span><span class="token punctuation">)</span>
gini_thresholds <span class="token operator">=</span> np<span class="token punctuation">.</span>linspace<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span><span class="token number">0.5</span><span class="token punctuation">,</span><span class="token number">50</span><span class="token punctuation">)</span>
param_grid <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">{</span><span class="token string">'criterion'</span><span class="token punctuation">:</span><span class="token punctuation">[</span><span class="token string">'entropy'</span><span class="token punctuation">]</span><span class="token punctuation">,</span><span class="token string">'min_impurity_split'</span><span class="token punctuation">:</span>entropy_thresholds<span class="token punctuation">}</span><span class="token punctuation">,</span>
              <span class="token punctuation">{</span><span class="token string">'criterion'</span><span class="token punctuation">:</span><span class="token punctuation">[</span><span class="token string">'gini'</span><span class="token punctuation">]</span><span class="token punctuation">,</span><span class="token string">'min_impurity_split'</span><span class="token punctuation">:</span>gini_thresholds<span class="token punctuation">}</span><span class="token punctuation">,</span>
              <span class="token punctuation">{</span><span class="token string">'max_depth'</span><span class="token punctuation">:</span>range<span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">}</span><span class="token punctuation">,</span>
              <span class="token punctuation">{</span><span class="token string">'min_samples_split'</span><span class="token punctuation">:</span>range<span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">30</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">}</span><span class="token punctuation">]</span>
clf<span class="token operator">=</span>GridSearchCV<span class="token punctuation">(</span>DecisionTreeClassifier<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>param_grid<span class="token punctuation">,</span>cv<span class="token operator">=</span><span class="token number">5</span><span class="token punctuation">)</span>
clf<span class="token punctuation">.</span>fit<span class="token punctuation">(</span>X<span class="token punctuation">,</span>y<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'best param: {0}\nbest score: {1}'</span><span class="token punctuation">.</span>format<span class="token punctuation">(</span>clf<span class="token punctuation">.</span>best_params_<span class="token punctuation">,</span>clf<span class="token punctuation">.</span>best_score_<span class="token punctuation">)</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>输出如下：</p>
<pre class="line-numbers language-python"><code class="language-python">best param<span class="token punctuation">:</span> <span class="token punctuation">{</span><span class="token string">'criterion'</span><span class="token punctuation">:</span> <span class="token string">'entropy'</span><span class="token punctuation">,</span> <span class="token string">'min_impurity_split'</span><span class="token punctuation">:</span> <span class="token number">0.5306122448979591</span><span class="token punctuation">}</span>
best score<span class="token punctuation">:</span> <span class="token number">0.8305818843763729</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>代码关键部分还是<code>param_grid</code>参数，它是一个列表，列表中的每个元素都是字典。例如：针对列表中的第一个字典，选择信息熵作为决策树特征选择的判断标准，同时其阈值范围是[0,1]之间分了50等份。<code>GridSearchCV</code>会针对列表中的每个字典进行迭代，最终比较列表中每个字典所对应的参数组合，选择出最优的参数。关于<code>GridSearchCV</code>的更多详情可参考<a href="http://lijiancheng0614.github.io/scikit-learn/modules/generated/sklearn.grid_search.GridSearchCV.html" target="_blank" rel="noopener">官方文档</a>。</p>
<p>最后基于好奇，使用最优参数的决策树到底是什么样呢？我们可以使用 <code>sklearn.tree.export_graphviz()</code> 函数把决策树模型导出到文件中，然后使用<code>graphviz</code>工具包生成决策树示意图。</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">from</span> sklearn<span class="token punctuation">.</span>tree <span class="token keyword">import</span> export_graphviz

columns <span class="token operator">=</span> train<span class="token punctuation">.</span>columns<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">:</span><span class="token punctuation">]</span>
<span class="token comment" spellcheck="true"># 导出 titanic.dot 文件</span>
<span class="token keyword">with</span> open<span class="token punctuation">(</span><span class="token string">"E:/titanic.dot"</span><span class="token punctuation">,</span> <span class="token string">'w'</span><span class="token punctuation">)</span> <span class="token keyword">as</span> f<span class="token punctuation">:</span>
    f <span class="token operator">=</span> export_graphviz<span class="token punctuation">(</span>clf<span class="token punctuation">,</span> out_file<span class="token operator">=</span>f<span class="token punctuation">,</span>feature_names<span class="token operator">=</span>columns<span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 1. conda安装 graphviz ：conda install python-graphviz </span>
<span class="token comment" spellcheck="true"># 2. 运行 `dot -Tpdf titanic.dot -o titanic.pdf` </span>
<span class="token comment" spellcheck="true"># 3. 在当前目录查看生成的决策树 titanic.png</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>最优参数的决策树就长这个样子</p>
<p><img src="/medias/loading.gif" data-original="https://cdn.jsdelivr.net/gh/dongzhougu/imageuse1/image-20200630185703496.png" alt="image-20200630185703496"></p>
<hr>
<h2 id="5-集合算法"><a href="#5-集合算法" class="headerlink" title="5.集合算法"></a>5.集合算法</h2><p>集合算法（Ensemble）是一种元算法（Meta-algorithm），它利用统计学采样原理，训练出成百上千个不同的算法模型。当需要预测一个新样本时，使用这些模型分别对这个样本进行预测，然后采样少数服从多数的原则，决定新样本的类别。集合算法可以有效地解决过拟合问题。在scikit-learn 里，所有的集合算法都实现在<code>sklearn.ensemble</code>包里。</p>
<h3 id="5-1-自助聚合算法Bagging"><a href="#5-1-自助聚合算法Bagging" class="headerlink" title="5.1 自助聚合算法Bagging"></a>5.1 自助聚合算法Bagging</h3><p>自助聚合（Bagging，Bootstrap Aggregating的缩写）的核心思想是，采用有放回的采样规则，从m个样本的原数据集里进行n次采样（n&lt;=m），构成一个包含n个样本的新训练数据集。重复这个过程B次，得到B个模型，当有新样本需要预测时，拿这B个模型分别对这个样本进行预测，然后采用投票方式（回归问题）得到新样本的预测值。</p>
<p>所谓的有放回采样规则是指，在m个数据集里，随机取出一个样本放到新数据集里，然后把这个样本放回到原数据集里，继续随机采样，直到到达采样次数n为止。由此可见，随机采样出的数据集里可能有重复数据，并且原数据集的每一个数据不一定都出现在新数据集里。</p>
<p>单一模型往往容易对数据噪声敏感，从而造成高方差（High Variance）。自助聚合算法可以降低对数据噪声的敏感性，从而提高模型准确性和稳定性。这种方法不需要额外的输入，只是简单地对同一个数据集训练出多个模型即可实现。当然这并不是说没有代价，自助聚合算法一般会增加模型训练的计算量。</p>
<p>在<code>scikit-learn</code>里，由<code>BaggingClassifier</code>类和B<code>aggingRegressor</code>类分别实现了分类和回归的Bagging算法。</p>
<h3 id="5-2-正向激励算法Boosting"><a href="#5-2-正向激励算法Boosting" class="headerlink" title="5.2 正向激励算法Boosting"></a>5.2 正向激励算法Boosting</h3><p>正向激励算法（Boosting）的基本原理是，初始化时，针对有m个训练样本的数据集，给每个样本都分配一个初始权重，然后使用这个带有权重的数据集来训练模型。训练出模型之后，针对这个模型预测错误的那些样本，增加其权重，然后拿这个更新过权重的数据集来训练出一个新的模型。重复这个过程B次，就可以训练出B个模型。</p>
<p>Boosting算法和Bagging算法的区别如下：</p>
<ul>
<li>采样规则不同：Bagging算法是采样有放回的随机采样规则。而Boosting算法是使用增加预测错误样本权重的方法，相当于加强了对预测错误的样本的学习力度，从而提高模型的准确性。</li>
<li>训练方式不同：Bagging算法可以并行训练多个模型。而Boosting算法只能串行训练，因为下一个模型依赖上一个模型的预测结果。</li>
<li>模型权重不同：Bagging算法训练出来的B个模型的权重是一样的。而Boosting算法训练出来的B个模型本身带有权重信息，在对新样本进行预测时，每个模型的权重是不一样的。单个模型的权重由模型训练的效果来决定，即准确性高的模型权重更高。</li>
</ul>
<p>Boosting算法有很多种实现，其中最著名的是 <code>AdaBoosting</code> 算法。在 <code>scikit-learn</code> 里由<code>AdaBoostingClassifier</code>类和 <code>AdaBoostingRegression</code>类分别实现Boosting分类和Boosting回归。</p>
<h3 id="5-3-随机森林"><a href="#5-3-随机森林" class="headerlink" title="5.3 随机森林"></a>5.3 随机森林</h3><p>随机森林（RF，Random Forest）在自助聚合算法（Bagging）的基础上更进一步，对特征应用自助聚合算法。即，每次训练时，不拿所有的特征来训练，而是随机选择一个特征的子集来进行训练。随机森林算法有两个关键参数，一是构建的决策树的个数t，二是构建单棵决策树特征的个数f。</p>
<p>假设，针对一个有m个样本、n个特征的数据集，则其算法原理如下：</p>
<h4 id="单棵决策树的构建"><a href="#单棵决策树的构建" class="headerlink" title="单棵决策树的构建"></a>单棵决策树的构建</h4><ul>
<li>采用有放回采样，从原数据集中经过m次采样，获取到一个m个样本的数据集（这个数据集里可能有重复的样本）</li>
<li>从n个特征里，采用无放回采样规则，从中取出f个特征作为输入特征。</li>
<li>重复上述过程t次，构建出t棵决策树。</li>
</ul>
<h4 id="随机森林的分类结果"><a href="#随机森林的分类结果" class="headerlink" title="随机森林的分类结果"></a>随机森林的分类结果</h4><p> 生成t棵决策树之后，对于每个新的测试样例，集合多棵决策树的预测结果来作为随机森林的预测结果。具体为，如果是回归问题，取t棵决策树的预测值的平均值作为随机森林的预测结果；如果是分类问题，采取少数服从多数的原则，取单棵决策树预测最多的那个类别作为随机森林的分类结果。</p>
<blockquote>
<p>思考：为什么随机森林要选取特征的子集来构建决策树？</p>
</blockquote>
<p> 假如某个输入特征对预测结果是强关联的，那么如果选择全部的特征来构建决策树，这个特征都会体现在所有的决策树里面。由于这个特征和预测结果强关联，会造成所有的决策树都强烈地反映这个特征的“倾向性”，从而导致无法很好地解决过拟合问题。我们在讨论线性回归算法时，通过增加正则项来解决过拟合，它的原理就是确保每个特征都对预测结果有少量的贡献，从而避免单个特征对预测结果有过大贡献导致的过拟合问题。这里的原理是一样的。</p>
<p>在 <code>scikit-learn</code> 里由 <code>RandomForestClassifier</code> 类和 <code>RandomForestRegression</code> 类分别实现随机森林的分类算法和随机森林的回归算法。</p>
<h3 id="5-4-ExtraTrees算法"><a href="#5-4-ExtraTrees算法" class="headerlink" title="5.4 ExtraTrees算法"></a>5.4 ExtraTrees算法</h3><p>ExtraTrees，叫做极限树或者极端随机树。随机森林在构建决策树的过程中，会使用信息熵或者基尼不纯度，然后选择信息增益最大的特征来进行分裂。而 <code>ExtraTrees</code> 是直接从所有特征里随机选择一个特征来分裂，从而避免了过拟合问题。</p>
<p>在<code>scikit-learn</code>里，由<code>ExtraTreesClassifier</code>类和 <code>ExtraTreesRegression</code> 类分别实现 <code>ExtraTrees</code> 的分类算法和 ExtraTrees 的回归算法。</p>
<hr>
<h2 id="6-扩展阅读"><a href="#6-扩展阅读" class="headerlink" title="6. 扩展阅读"></a>6. 扩展阅读</h2><h3 id="6-1-熵和条件熵"><a href="#6-1-熵和条件熵" class="headerlink" title="6.1 熵和条件熵"></a>6.1 熵和条件熵</h3><p>在决策树创建过程中，我们会计算以某个特征创建分支后的子数据集的信息熵。用数学语言描述实际上是计算条件熵，即满足某个条件的信息熵。</p>
<p>关于信息熵和条件熵的相关概念，可以阅读吴军老师的<a href="https://baike.baidu.com/item/%E6%95%B0%E5%AD%A6%E4%B9%8B%E7%BE%8E/1580521?fr=aladdin" target="_blank" rel="noopener">《数学之美》</a>里”信息的度量和作用”一文。《数学之美》这本书，吴军老师用平实的语言，把复杂的数学概念解释的入木三分，即使你只有高中的数学水平，也可以领略到数学的“优雅”和“威力”。</p>
<h3 id="6-2-决策树的构建算法"><a href="#6-2-决策树的构建算法" class="headerlink" title="6.2 决策树的构建算法"></a>6.2 决策树的构建算法</h3><p>本文重点介绍的决策树构建算法是ID3算法，它是1986年由Ross Quinlan提出的。1993年，该算法作者发布了新的决策树构建算法C4.5，作为ID3算法的改进，主要体现在：</p>
<ul>
<li>增加了对连续值的处理，方法是使用一个阈值作为连续值的划分条件，从而把数据离散化。</li>
<li>自动处理特征值缺失问题，处理方法是直接把这个特征抛弃，不参与计算信息增益比。</li>
<li>使用信息增益比作为特征选择标准。</li>
<li>采用后剪枝算法处理过拟合，即在决策树创建完成之后，再通过合并叶子节点的方式进行剪枝。</li>
</ul>
<p>此后，该算法作者又发布了改进的商业版本C5.0，它运算效率更高，使用内存更小，创建出来的决策树更小，并且准确性更高，适合大数据集的决策树构建。</p>
<p>除了前面介绍的使用基尼不纯度来构建决策树的CART算法之外，还有其他知名的决策树构建算法，如CHAID算法、MARS算法等。这里不再详述。</p>
<script>
        document.querySelectorAll('.github-emoji')
          .forEach(el => {
            if (!el.dataset.src) { return; }
            const img = document.createElement('img');
            img.style = 'display:none !important;';
            img.src = el.dataset.src;
            img.addEventListener('error', () => {
              img.remove();
              el.style.color = 'inherit';
              el.style.backgroundImage = 'none';
              el.style.background = 'none';
            });
            img.addEventListener('load', () => {
              img.remove();
            });
            document.body.appendChild(img);
          });
      </script>
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">DongZhou</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://dongzhougu.github.io/2020/06/30/scikit-learn-xi-lie-wu-jue-ce-shu/">https://dongzhougu.github.io/2020/06/30/scikit-learn-xi-lie-wu-jue-ce-shu/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">DongZhou</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/">
                                    <span class="chip bg-color">基础知识</span>
                                </a>
                            
                                <a href="/tags/ML%E7%AE%97%E6%B3%95/">
                                    <span class="chip bg-color">ML算法</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="https://cdn.jsdelivr.net/gh/DongZhouGu/DongZhouGu.github.io/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="https://cdn.jsdelivr.net/gh/DongZhouGu/DongZhouGu.github.io/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }

    #vcomments textarea {
        box-sizing: border-box;
        background: url("/medias/comment_bg.png") 100% 100% no-repeat;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #4cbf30;
        font-weight: 500;
        text-decoration: none;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
        display: list-item;
        line-height: 1.8rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }
</style>

<div class="card valine-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="vcomments" class="card-content" style="display: grid">
    </div>
</div>

<script src="/libs/valine/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/DongZhouGu/DongZhouGu.github.io/libs/valine/Valine.min.js"></script>
<script>
    new Valine({
        el: '#vcomments',
        appId: 'RPCuj0HNm1eqAREO6c5T7nSJ-gzGzoHsz',
        appKey: 'laCdQbWLFWOWdkXVM3RxoXGe',
        notify: 'false' === 'true',
        verify: 'false' === 'true',
        visitor: 'true' === 'true',
        avatar: 'mm',
        pageSize: '10',
        lang: 'zh-cn',
        placeholder: '快来留言吧'
    });
</script>

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2020/06/30/emoji-test/">
                    <div class="card-image">
                        
                        
                        <img src="https://cdn.jsdelivr.net/gh/DongZhouGu/DongZhouGu.github.io/medias/featureimages/4.jpg" class="responsive-img" alt="emoji test">
                        
                        <span class="card-title">emoji test</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            啊实打实大萨达萨达
😄
😄
😄
🌈
🌈 asdasdasdasdasdasd
🌈 asdasdasdasdasdasdemoji  速查https://www.webfx.com/tools/emoji-cheat-sheet/
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-06-30
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E6%95%99%E7%A8%8B/" class="post-category">
                                    教程
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Hexo/">
                        <span class="chip bg-color">Hexo</span>
                    </a>
                    
                    <a href="/tags/%E5%8D%9A%E5%AE%A2%E6%90%AD%E5%BB%BA/">
                        <span class="chip bg-color">博客搭建</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2020/06/30/scikit-learn-xi-lie-si-luo-ji-hui-gui/">
                    <div class="card-image">
                        
                        
                        <img src="https://cdn.jsdelivr.net/gh/DongZhouGu/DongZhouGu.github.io/medias/featureimages/9.jpg" class="responsive-img" alt="scikit-learn系列四：逻辑回归">
                        
                        <span class="card-title">scikit-learn系列四：逻辑回归</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            实现逻辑回归算法，原理解释+癌症检测案例
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-06-30
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/" class="post-category">
                                    机器学习
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/">
                        <span class="chip bg-color">基础知识</span>
                    </a>
                    
                    <a href="/tags/ML%E7%AE%97%E6%B3%95/">
                        <span class="chip bg-color">ML算法</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="https://cdn.jsdelivr.net/gh/DongZhouGu/DongZhouGu.github.io/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>


<script src="https://cdn.bootcss.com/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script>
    MathJax.Hub.Config({
        tex2jax: {inlineMath: [['$', '$'], ['\(', '\)']]}
    });
</script>



<footer class="page-footer bg-color">
    
    <div class="container row center-align" style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">2020</span>
            <a href="/about" target="_blank">DongZhou</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">60.5k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2020";
                    var startMonth = "6";
                    var startDate = "27";
                    var startHour = "0";
                    var startMinute = "0";
                    var startSecond = "0";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/DongZhouGu" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:gdz678@163.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1596586942" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1596586942" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


<!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/search.xml", 'searchInput', 'searchResult');
});
</script>

<!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


<script src=" https://cdn.jsdelivr.net/gh/DongZhouGu/DongZhouGu.github.io/libs/materialize/materialize.min.js"></script>
<script src=" https://cdn.jsdelivr.net/gh/DongZhouGu/DongZhouGu.github.io/libs/masonry/masonry.pkgd.min.js"></script>
<script src=" https://cdn.jsdelivr.net/gh/DongZhouGu/DongZhouGu.github.io/libs/aos/aos.js"></script>
<script src=" https://cdn.jsdelivr.net/gh/DongZhouGu/DongZhouGu.github.io/libs/scrollprogress/scrollProgress.min.js"></script>
<script src=" https://cdn.jsdelivr.net/gh/DongZhouGu/DongZhouGu.github.io/libs/lightGallery/js/lightgallery-all.min.js"></script>
<script src=" /js/matery.js"></script>

<!-- Baidu Analytics -->

<!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>


<script src=" https://cdn.jsdelivr.net/gh/DongZhouGu/DongZhouGu.github.io/libs/others/clicklove.js" async="async"></script>


<script async src=" https://cdn.jsdelivr.net/gh/DongZhouGu/DongZhouGu.github.io/libs/others/busuanzi.pure.mini.js"></script>













<script src=" https://cdn.jsdelivr.net/gh/DongZhouGu/DongZhouGu.github.io/libs/instantpage/instantpage.js" type="module"></script>


<script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(n){n.imageLazyLoadSetting.processImages=o;var i=n.imageLazyLoadSetting.isSPA,r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]"));function o(){i&&(r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")));for(var t,e,a=0;a<r.length;a++)t=r[a],e=void 0,0<=(e=t.getBoundingClientRect()).bottom&&0<=e.left&&e.top<=(n.innerHeight||document.documentElement.clientHeight)&&function(){var t,e,n,i,o=r[a];t=o,e=function(){r=r.filter(function(t){return o!==t})},n=new Image,i=t.getAttribute("data-original"),n.onload=function(){t.src=i,e&&e()},n.src=i}()}o(),n.addEventListener("scroll",function(){var t,e;t=o,e=n,clearTimeout(t.tId),t.tId=setTimeout(function(){t.call(e)},500)})}(this);</script></body>

</html>
